package com.mr.web.dwr;

import javax.servlet.ServletContext;

import org.directwebremoting.Container;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.extend.ConverterManager;
import org.directwebremoting.extend.ScriptBufferUtil;
import org.directwebremoting.impl.DefaultServerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;

public class DWRUtils {
   private static ServletContext context;
   private static WebApplicationContext appContext;
   private static final transient Logger log = LoggerFactory.getLogger(DWRUtils.class);
   public DWRUtils(){}
   public static ServletContext getContext() {
      return context;
   }

   public static void setContext(ServletContext context) {
      DWRUtils.context = context;
   }
   public static ConverterManager getConverterManager() {
      DefaultServerContext serverContext = (DefaultServerContext)context.getAttribute("org.directwebremoting.impl.ServerContext");
      Container container = serverContext.getContainer();
      ConverterManager cm = (ConverterManager) container.getBean("org.directwebremoting.extend.ConverterManager");
      return cm;
   }
   public static String getScriptObject(String scriptObjectName, Object modelObject){
      ConverterManager converterManager = getConverterManager();
      ScriptBuffer sb = new ScriptBuffer();
      sb.appendScript("var " + scriptObjectName+"=")
         .appendData(modelObject);
      String js=null;
      try {
         js = ScriptBufferUtil.createOutput(sb, converterManager);
      } catch (Exception e) {
         log.warn("", e);
      }
      return js;
   }
   
	public static WebApplicationContext getAppContext() {
		return appContext;
	}
	public static void setAppContext(WebApplicationContext appContext) {
		DWRUtils.appContext = appContext;
	}
}
